﻿///////////////////////////////////////////////////
//项目：基于手机蓝牙的可配置的计算机应用程序遥控
//作者：华南理工：曹炼强 林伟彬
//本文件功能：控制应用程序
//////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.Collections;
using System.Xml;
namespace BCC
{
    class Control
    {
        [DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern int GetWindowText(IntPtr hWnd, [Out, MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpString, int nMaxCount);
        [DllImport("user32.dll", EntryPoint = "keybd_event", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern void keybd_event(byte vk, byte scan, int flags, int extrainfo);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern bool OpenIcon(IntPtr hWnd);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern bool IsWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(String sClassName, String sAppName);
        [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll", EntryPoint = "GetForegroundWindow")]
        private static extern IntPtr GetForegroundWindow();
        [DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId")]
        public static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref uint lpdwProcessId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, uint lParam);
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern bool IsZoomed(IntPtr hWnd);
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern bool IsIconic(IntPtr hWnd);
        [DllImport("user32.dll")]
        public static extern IntPtr ShowWindow(IntPtr hWnd, int nCmdShow);
        int SW_SHOWNORMAL = 1;
        int SW_SHOWMINIMIZED = 2;
        int SW_SHOWMAXIMIZED = 3;

        [DllImport("user32.dll")]
        public static extern UInt32 SendInput(UInt32 nInputs, Input[] pInputs, int cbSize);

        [StructLayout(LayoutKind.Explicit)]
        public struct Input
        {
            [FieldOffset(0)]
            public Int32 type;
            [FieldOffset(4)]
            public MouseInput mi;
            [FieldOffset(4)]
            public tagKEYBDINPUT ki;
            [FieldOffset(4)]
            public tagHARDWAREINPUT hi;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MouseInput
        {
            public Int32 dx;
            public Int32 dy;
            public Int32 Mousedata;
            public Int32 dwFlag;
            public Int32 time;
            public IntPtr dwExtraInfo;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct tagKEYBDINPUT
        {
            public Int16 wVk;
            public Int16 wScan;
            public Int32 dwFlags;
            Int32 time;
            IntPtr dwExtraInfo;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct tagHARDWAREINPUT
        {
            Int32 uMsg;
            Int16 wParamL;
            Int16 wParamH;
        }

        [DllImport("user32.dll")]
        static extern bool SetCursorPos(int X, int Y);
        [DllImport("user32.dll")]
        public static extern bool GetCursorPos(out Point pt);
        [DllImport("user32.dll")]
        static extern void mouse_event(MouseEventFlag flags, int dx, int dy, int data, UIntPtr extraInfo);
        [Flags]
        enum MouseEventFlag : uint
        {
            Move = 0x0001,
            LeftDown = 0x0002,
            LeftUp = 0x0004,
            RightDown = 0x0008,
            RightUp = 0x0010,
            MiddleDown = 0x0020,
            MiddleUp = 0x0040,
            XDown = 0x0080,
            XUp = 0x0100,
            Wheel = 0x0800,
            VirtualDesk = 0x4000,
            Absolute = 0x8000
        }

        private Thread clipboardThread;
        private Thread sendMusicName;
        public IntPtr parentHandle;
        public string xmlFile;
        public string copyText;
        private int curAppId = new int();
        private IntPtr curWinHandle = new IntPtr();
        private List<appItem> items = new List<appItem>();
        private xmlClass xml = new xmlClass();

        MouseInput myMinput = new MouseInput();
        Input[] myInput = new Input[1];
        const uint WM_APPCOMMAND = 0x319;
        const uint APPCOMMAND_VOLUME_UP = 0x0a;
        const uint APPCOMMAND_VOLUME_DOWN = 0x09;
        const uint APPCOMMAND_VOLUME_MUTE = 0x08;

        const int MouseEvent_Absolute = 0x8000;
        const int MouserEvent_Hwheel = 0x01000;
        const int MouseEvent_Move = 0x0001;
        const int MouseEvent_Move_noCoalesce = 0x2000;
        const int MouseEvent_LeftDown = 0x0002;
        const int MouseEvent_LeftUp = 0x0004;
        const int MouseEvent_MiddleDown = 0x0020;
        const int MouseEvent_MiddleUp = 0x0040;
        const int MouseEvent_RightDown = 0x0008;
        const int MouseEvent_RightUp = 0x0010;
        const int MouseEvent_Wheel = 0x0800;
        const int MousseEvent_XUp = 0x0100;
        const int MousseEvent_XDown = 0x0080;

        //验证解析命令字符串函数
        //返回1正常 返回2 命令不完整 返回3命令格式错误 返回-1 退出
        public int ControlFuncation(string theCmd)
        {

            string[] sArray = theCmd.Split('|');
            if (sArray.Length >= 2)
            {
                string cmdHead = sArray[0];
                string cmdContent = sArray[1];
                /*string cmdTail = sArray[2];
                if (cmdTail.Length > 3)
                {
                    cmdTail = cmdTail.Remove(3);
                }
                if (!cmdTail.Equals("end"))
                {
                    //MessageBox.Show("命令不完整");
                    return 2;
                }*/
                switch (cmdHead)
                {
                    
                    case "exit":
                        return -1;
                    case "openapp":
                        openApp(cmdContent);
                        break;
                    case "openmusic":
                        openMusic(cmdContent);
                        break;
                    case "opengame":
                        openGame(cmdContent);
                        break;
                    case "closemusic":
                        closeMusic();
                        break;
                    case "key":
                        ctrlApp(cmdContent);
                        break;
                    case "keydown":
                        keyEvent(0, cmdContent);
                        break;
                    case "keyup":
                        keyEvent(2, cmdContent);
                        break;
                    case "do":
                        ctrlApp(curWinHandle, cmdContent);
                        break;
                    case "applist":
                        sendList(cmdContent);
                        break;
                    case "switchto":
                        switchApp(cmdContent);
                        break;
                    case "closeapp":
                        closeApp(cmdContent);
                        break;
                    case "system":
                        ctrlSystem(cmdContent);
                        break;
                    case "text":
                        textWrite(cmdContent);
                        break;
                    case "ack":
                        sendAck();
                        break;
                    case "move":
                        mouseMove(cmdContent);
                        break;
                    case "move2":
                        mouseMove2(cmdContent);
                        break;
                    case "leftclick":
                        mouseLeftClick();
                        break;
                    case "wheel":
                        wheelMove(cmdContent);
                        break;
                    case "updown":
                        mouseUpDown(cmdContent);
                        break;
                    case "max":
                        winMax();
                        break;
                    case "min":
                        winMin();
                        break;

                }
                return 1;
            }
            else
            {
                //return 3;
                MessageBox.Show("命令不完整");
                return 2;
            }
        }
        public void ctrlSystem(string cmdContent)
        {
            switch (cmdContent)
            {
                case "shutdown":
                    doCmd("shutdown -s -t 30");
                    break;
                case "reboot":
                    doCmd("shutdown -r -t 30");
                    break;
                case "cancle":
                    doCmd("shutdown -a");
                    break;
                case "volumeup":
                    SendMessage(this.parentHandle, WM_APPCOMMAND, 0x30292, APPCOMMAND_VOLUME_UP * 0x10000);
                    break;
                case "volumedown":
                    SendMessage(this.parentHandle, WM_APPCOMMAND, 0x30292, APPCOMMAND_VOLUME_DOWN * 0x10000);
                    break;
                case "volumemute":
                    SendMessage(this.parentHandle, WM_APPCOMMAND, 0x200eb0, APPCOMMAND_VOLUME_MUTE * 0x10000);
                    break;
            }
        }

        public void textWrite(string cmdContent)
        {
            copyText = cmdContent;
            clipboardThread = new Thread(new ThreadStart(this.clipboard));
            clipboardThread.SetApartmentState(ApartmentState.STA);
            clipboardThread.Start();
        }
        public void clipboard()
        {
            Clipboard.SetDataObject(copyText, true);
            //Ctrl+V
            ctrlApp("ControlKey+V");
            clipboardThread.Abort();
        }
        public void doCmd(string cmd)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.WriteLine(cmd);
            p.StandardInput.WriteLine("Exit");
            p.WaitForExit();
            p.Close();
        }

        public bool openMusic(string appName)
        {
            string sendOk = "openapp|ok:";
            string sendErr = "openapp|err:";
            string appAddress = xml.findAppAddress(xmlFile, appName);
            string className = "";
            if (appName.ToLower().Contains("kugou") || appName.ToLower().Contains("kugoo"))
                className = "KugouMainPlayer";
            if (appName.ToLower().Contains("ttplayer"))
                className = "TTPlayer_PlayerWnd";
            if (appName.ToLower().Contains("kwmusic"))
                className = "kwmusicmaindlg";
            if (appName.ToLower().Contains("qqmusic"))
                className = "TXGuiFoundation";
            curWinHandle = FindWindow(className, null);
            string sendStr = xml.findKeyValue(xmlFile, appName);
            sendMusicName = new Thread(new ThreadStart(this.sendMusic));
            if (curWinHandle != IntPtr.Zero)
            {
                if (SetForegroundWindow(curWinHandle))
                    OpenIcon(curWinHandle);
                int length = sendStr.Length;
                if (length == 0)
                {
                    Console.WriteLine("查找配置信息为空");
                    Server.Send(sendErr);
                    return false;
                }
                sendStr = "config|" + sendStr + ":";
                Server.Send(sendStr);
                Server.Send(sendOk);
                sendMusicName.Start();
                return true;
            }
            try
            {
                Process proc = Process.Start(appAddress);
                proc.WaitForInputIdle();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Thread.Sleep(1000);
            int cnt = 3;
            while (cnt > 0 && curWinHandle == IntPtr.Zero)
            {
                curWinHandle = FindWindow(className, null);
                cnt--;
            }
            if (curWinHandle != IntPtr.Zero)
            {
                int length = sendStr.Length;
                if (length == 0)
                {
                    Console.WriteLine("查找配置信息为空");
                    Server.Send(sendErr);
                    return false;
                }
                sendStr = "config|" + sendStr + ":";
                Server.Send(sendStr);
                Server.Send(sendOk);
                sendMusicName.Start();
                return true;
            }
            Server.Send(sendStr);
            Server.Send(sendErr);
            return false;
        }

        public void closeMusic()
        {
            if (sendMusicName != null)
                sendMusicName.Abort();
        }
        public void sendMusic()
        {
            StringBuilder sb = new StringBuilder(128);
            string str = "";
            while (true)
            {
                if (curWinHandle != IntPtr.Zero)
                {
                    GetWindowText(curWinHandle, sb, sb.Capacity);
                    str = "musicname|" + sb.ToString() + ":";
                    Server.Send(str);
                }
                Thread.Sleep(3000);
            }
        }

        //模拟游戏
        public bool openGame(string appName)
        {
            string sendOk = "openapp|ok:";
            string sendErr = "openapp|err:";
            string appAddress = xml.findAppAddress(xmlFile, appName);
            string sendStr = xml.findKeyValue(xmlFile, appName);

            try
            {
                Process proc = Process.Start(appAddress);
                proc.WaitForInputIdle();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Thread.Sleep(1000);

            int length = sendStr.Length;
            if (length == 0)
            {
                Console.WriteLine("查找配置信息为空");
                Server.Send(sendErr);
                return false;
            }
            sendStr = "config|" + sendStr + ":";
            Server.Send(sendStr);
            Server.Send(sendOk);
            return true;
        }

        //打开应用程序函数
        public bool openApp(string appName)
        {
            string sendOk = "openapp|ok:";
            string sendErr = "openapp|err:";
            if (switchApp(appName))
            {
                Server.Send(sendOk);
                return true;
            }
            Console.WriteLine("begin to open the process");
            string appAddress = xml.findAppAddress(xmlFile, appName);
            if (appAddress == "")
            {
                //Console.WriteLine("不能找到程序路径");
                Server.Send(sendErr);
                return false;
            }
            bool ret = true;
            curWinHandle = IntPtr.Zero;
            Process proc = new Process();
            try
            {
                string[] adtmp = appAddress.Split('\\');
                string realAppName = adtmp[adtmp.Length - 1].Split('.')[0];
                // 标志程序是否已经在运行
                bool isrunning = false;
                curWinHandle = FindWindowByName.GetTheWindowHandle(appName);
                if (curWinHandle != IntPtr.Zero)
                {
                    isrunning = true;
                    if (SetForegroundWindow(curWinHandle))
                        OpenIcon(curWinHandle);
                    uint uid = 0;
                    GetWindowThreadProcessId(curWinHandle, ref uid);
                    curAppId = (int)uid;
                }
                if (!isrunning)
                {
                    proc = Process.Start(appAddress);
                    proc.WaitForInputIdle();
                    Thread.Sleep(1000);
                    curAppId = proc.Id;
                    curWinHandle = proc.MainWindowHandle;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                ret = true;
            }
            finally
            {
                //如果没能直接获得进程主窗口则遍历所有窗口查找进程的窗口
                if (curWinHandle == IntPtr.Zero)
                {
                    curWinHandle = FindWindowByName.GetTheWindowHandle(appName);
                    if (curWinHandle == IntPtr.Zero)
                        ret = true;
                    else
                    {
                        uint uid = 0;
                        GetWindowThreadProcessId(curWinHandle, ref uid);
                        curAppId = (int)uid;
                    }
                }
                if (curWinHandle != IntPtr.Zero)
                {
                    appItem item = new appItem();
                    item.id = curAppId;
                    item.hwnd = curWinHandle;
                    item.name = appName;
                    items.Add(item);
                }
                string sendStr = xml.findKeyValue(xmlFile, appName);
                int length = sendStr.Length;
                if (length == 0)
                {
                    Console.WriteLine("查找配置信息为空");
                    Server.Send(sendErr);
                    ret = false;
                }
                if (ret)
                {
                    sendStr = "config|" + sendStr + ":";
                    Server.Send(sendStr);
                    Server.Send(sendOk);
                }
                ret = true;
            }
            return ret;
        }

        //控制应用程序函数,不需窗口
        public bool ctrlApp(string cmdContent)
        {
            string[] sArray = cmdContent.Split('+');
            byte[] sByte = new byte[sArray.Length];
            for (int i = 0; i < sArray.Length; i++)
            {
                sByte[i] = strtobyte(sArray[i]);
            }
            for (int i = 0; i < sByte.Length; i++)
                keybd_event(sByte[i], 0, 0, 0);
            for (int i = sByte.Length-1; i >= 0; i--)
                keybd_event(sByte[i], 0, 2, 0);
            return true;
        }

        public bool keyEvent(int flag, string cmdContent)
        {
            string[] sArray = cmdContent.Split('+');
            byte[] sByte = new byte[sArray.Length];
            for (int i = 0; i < sArray.Length; i++)
            {
                sByte[i] = strtobyte(sArray[i]);
            }
            for (int i = 0; i < sByte.Length; i++)
            {
                keybd_event(sByte[i], 0, flag, 0);
            }
            return true;
        }
        //控制应用程序函数
        public bool ctrlApp(IntPtr hwnd, string cmdContent)
        {
            //Debug.WriteLine(hwnd.ToString());
            string cmdKey = cmdKeys(cmdContent);
            IntPtr theHwnd;
            if (cmdContent.Equals(""))
            {
                return false;
            }
            try
            {
                theHwnd = GetForegroundWindow();
                if (theHwnd != hwnd)
                {
                    uint uid = 0;
                    GetWindowThreadProcessId(theHwnd, ref uid);
                    if (uid != curAppId)
                    {
                        hwnd = FindWindowByName.UpdateWind(hwnd);
                        if (hwnd == IntPtr.Zero)
                            return false;
                        curWinHandle = hwnd;
                        if (SetForegroundWindow(curWinHandle))
                            OpenIcon(curWinHandle);
                    }
                    Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                theHwnd = hwnd;
                Console.WriteLine(ex.Message);
            }
            try
            {
                SendKeys.SendWait(cmdKey);
                Thread.Sleep(100);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
        }

        //处理程序列表请求函数
        private bool sendList(string cmdContent)
        {
            xmlClass xml = new xmlClass();
            string sendStr = "";
            if (cmdContent.Equals("default"))
            {
                sendStr = xml.findApp(xmlFile);
            }
            else
            {
                sendStr = xml.findApp(cmdContent);
            }
            int length = sendStr.Length;
            if (length == 0)
            {
                Console.WriteLine("没有获得程序列表");
                return false;
            }
            sendStr = "applist|" + sendStr + ":";
            Server.Send(sendStr);
            return true;
        }

        //切换程序函数 切换成功换回true 否则返回false
        private bool switchApp(string cmdContent)
        {
            if (items == null)
            {
                return false;
            }
            foreach (appItem item in items)
            {
                if (item.name.Equals(cmdContent))
                {
                    curAppId = item.id;
                    curWinHandle = FindWindowByName.GetTheWindowHandle(cmdContent);
                    //对应进程已经关闭
                    if (curWinHandle == (IntPtr)0)
                    {
                        items.Remove(item);
                        return false;
                    }
                    uint uid = 0;
                    GetWindowThreadProcessId(curWinHandle, ref uid);
                    curAppId = (int)uid;
                    item.id = curAppId;
                    item.hwnd = curWinHandle;
                    if (SetForegroundWindow(curWinHandle))
                        OpenIcon(curWinHandle);
                    string sendStr = xml.findKeyValue(xmlFile, cmdContent);
                    int length = sendStr.Length;
                    if (length == 0)
                    {
                        Console.WriteLine("查找配置信息为空");
                        return false;
                    }
                    sendStr = "config|" + sendStr + ":";
                    Server.Send(sendStr);
                    return true;
                }
            }
            return false;
        }

        //关闭程序函数  //可能关不了
        private bool closeApp(string cmdContent)
        {
            int id = 0;
            foreach (appItem item in items)
            {
                if (item.name.Equals(cmdContent))
                {
                    id = item.id;
                    items.Remove(item);
                    break;
                }
            }
            if (id == 0)
            {
                Console.WriteLine("没有找到要关闭程序的id");
                return false;
            }
            try
            {
                //Process myProcess = Process.GetProcessById(id);
                //myProcess.Kill();
                string cmd = "taskkill /PID " + id + " /f /t";
                doCmd(cmd);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            return true;
        }

        //程序控制命令解析函数
        private string cmdKeys(string cmdContent)
        {
            string[] sArray = cmdContent.Split('+');
            int x = sArray.Length;
            if (x == 0)
            {
                MessageBox.Show("空命令");
            }
            if (x == 1)
            {
                return strtocmd(sArray[0]);
            }
            if (x == 2)
            {
                return strtocmd(sArray[0]) + strtocmd(sArray[1]);
            }
            if (x == 3)
            {
                return strtocmd(sArray[0]) + "(" + strtocmd(sArray[1]) + strtocmd(sArray[2]) + ")";
            }
            return "";
        }

        //字符串到Keys的转换
        private byte strtobyte(string str)
        {
            if (str == "")
                return 0;
            byte res = 0;
            char ch;
            ch = str.ToCharArray()[0];
            if (str.Length == 1)
            {
                if (ch >= 'a' && ch <= 'z')
                {
                    res = (byte)(ch - 32);
                    return res;
                }
                if (ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9')
                {
                    res = (byte)ch;
                    return res;
                }
            }

            //处理F1~F12
            if (ch == 'F')
            {
                string temp = str.Substring(1);
                int num = Int32.Parse(temp);
                res = (byte)(111 + num);
                return res;
            }
            switch (str)
            {
                case "Back": res = 8;
                    break;
                case "Tab": res = 9;
                    break;
                case "Return": res = 13;
                    break;
                case "Shift":
                case "ShiftKey": res = 16;
                    break;
                case "Control":
                case "ControlKey": res = 17;
                    break;
                case "Alt":
                case "Menu": res = 18;
                    break;
                case "Capital": res = 20;
                    break;
                case "Escape": res = 27;
                    break;
                case " ":
                case "Space": res = 32;
                    break;
                case "PageUp": res = 33;
                    break;
                case "Next":
                case "PageDown": res = 34;
                    break;
                case "End": res = 35;
                    break;
                case "Home": res = 36;
                    break;
                case "Left": res = 37;
                    break;
                case "Up": res = 38;
                    break;
                case "Right": res = 39;
                    break;
                case "Down": res = 40;
                    break;
                case "Insert": res = 45;
                    break;
                case "Delete": res = 46;
                    break;
                case "LWin":
                case "RWin":
                case "Win": res = 91;
                    break;
                case ";": res = 186;
                    break;
                case "=": res = 187;
                    break;
                case ",": res = 188;
                    break;
                case "-": res = 189;
                    break;
                case ".": res = 190;
                    break;
                case "/": res = 191;
                    break;
                case "`": res = 192;
                    break;
                case "[": res = 219;
                    break;
                case "\\": res = 220;
                    break;
                case "]": res = 221;
                    break;
                case "'": res = 222;
                    break;
            }
            return res;
        }

        //从命令字符串到系统命名转换函数
        private string strtocmd(string str)
        {
            string cmd;
            if (str.Length == 1)
            {
                cmd = str;
                return cmd;
            }
            switch (str)
            {
                case "Alt": cmd = "%";
                    break;
                case "Menu": cmd = "%";
                    break;
                case "Control": cmd = "^";
                    break;
                case "ControlKey": cmd = "^";
                    break;
                case "Shift": cmd = "+";
                    break;
                case "ShiftKey": cmd = "+";
                    break;
                case "Tab": cmd = "{TAB}";
                    break;
                case "Delete": cmd = "{DELETE}";
                    break;
                case "Insert": cmd = "{INSERT}";
                    break;
                case "NumLock": cmd = "{NUMLOCK}";
                    break;
                case "Capital": cmd = "{CAPSLOCK}";
                    break;
                case "Return": cmd = "{ENTER}";
                    break;
                case "Up": cmd = "{UP}";
                    break;
                case "Left": cmd = "{LEFT}";
                    break;
                case "Right": cmd = "{RIGHT}";
                    break;
                case "Down": cmd = "{DOWN}";
                    break;
                case "Escape": cmd = "{ESC}";
                    break;
                case "End": cmd = "{END}";
                    break;
                case "Help": cmd = "{HELP}";
                    break;
                case "Home": cmd = "{HOME}";
                    break;
                case "Break": cmd = "{BREAK}";
                    break;
                case "Back": cmd = "{BACKSPACE}";
                    break;
                case "PageUp": cmd = "{PGUP}";
                    break;
                case "Next": cmd = "{PGDN}";
                    break;
                case "ScrollLock": cmd = "{SCROLLLOCK}";
                    break;
                case "Add": cmd = "{ADD}";
                    break;
                case "Subtract": cmd = "{SUBTRACT}";
                    break;
                case "Multiply": cmd = "{MULTIPLY}";
                    break;
                case "Divide": cmd = "{DIVIDE}";
                    break;
                default: cmd = "{" + str + "}";
                    break;
            }
            return cmd;
        }
        private void sendAck()
        {
            string sendStr = "ack|null:";
            Server.Send(sendStr);
        }

        private void mouseMove(string cmdContent)
        {
            string[] sArray = cmdContent.Split(',');
            int delx, dely;
            Point cur;
            delx = Int32.Parse(sArray[0]);
            dely = Int32.Parse(sArray[1]);
            GetCursorPos(out cur);
            for (int i = 1; i <=  100; i++)
                SetCursorPos(cur.X + delx*i/100, cur.Y + dely*i/100);
        }

        private void mouseMove2(string cmdContent)
        {
            string[] sArray = cmdContent.Split(',');
            int delx, dely;
            //Point cur;
            delx = Int32.Parse(sArray[0]);
            dely = Int32.Parse(sArray[1]);
            //GetCursorPos(out cur);
            //for (int i = 1; i <=  100; i++)
            //    SetCursorPos(cur.X + delx*i/100, cur.Y + dely*i/100);
            for (int i = 0; i < 3; i++)
            {
                myMinput.dx = delx / 3;
                myMinput.dy = dely / 3;
                myMinput.Mousedata = 0;
                myMinput.dwFlag = MouseEvent_Move;
                myMinput.time = 0;

                myInput[0].type = 0;
                myInput[0].mi = myMinput;

                SendInput((uint)myInput.Length, myInput, Marshal.SizeOf(myInput[0].GetType()));
            }
        }

        private void mouseLeftClick()
        {
            mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, UIntPtr.Zero);
            mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
        }

        private void wheelMove(string cmdContent)
        {
            int del = Int32.Parse(cmdContent);
            mouse_event(MouseEventFlag.Wheel, 0, 0, -del*120, UIntPtr.Zero);
        }

        private void mouseUpDown(string cmdContent)
        {
            int which, flag;
            string[] sArray = cmdContent.Split(',');
            which = Int32.Parse(sArray[0]);
            flag = Int32.Parse(sArray[1]);
            flag = 1 << (1 + 2 * which + flag);
            mouse_event((MouseEventFlag)flag, 0, 0, 0, UIntPtr.Zero);
        }

        private void winMax()
        {
            IntPtr hWnd = GetForegroundWindow();
            //如果是最小化，则还原
            if (IsIconic(hWnd))
                ShowWindow(hWnd, SW_SHOWNORMAL);
            //否则都是最大化显示
            else
                ShowWindow(hWnd, SW_SHOWMAXIMIZED);
        }

        private void winMin()
        {
            IntPtr hWnd = GetForegroundWindow();
            //如果是最大化，则还原
            if (IsZoomed(hWnd))
                ShowWindow(hWnd, SW_SHOWNORMAL);
            //否则都是最小化显示
            else
                ShowWindow(hWnd, SW_SHOWMINIMIZED);
        }
    }


    //查找进程窗口类（根据进程的进程名找得到它的窗口的句柄）
    public class FindWindowByName
    {
        //任务栏中所有窗口的句柄，标题，类名
        public class taskWind
        {
            public IntPtr hwnd;
            public string className;
            public string text;
        }
        private static List<taskWind> tasks = null;
        public static string officePath = "";
        public static string officeVersion = "";
        public delegate bool WNDENUMPROC(IntPtr hwnd, int lParam);

        static FindWindowByName()
        {
            if (tasks == null)
            {
                tasks = new List<taskWind>();
            }
            if (officeVersion == "")
            {
                GetOfficePath(out officePath, out officeVersion);
            }
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern bool IsWindowVisible(IntPtr hWnd);

        [DllImport("user32", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
        public static extern IntPtr GetWindow(IntPtr hwnd, int wFlag);

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetClassName(IntPtr hWnd, [Out, MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll", EntryPoint = "EnumWindows", SetLastError = true)]
        public static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, int lParam);

        [DllImport("user32.dll", EntryPoint = "GetParent", SetLastError = true)]
        public static extern IntPtr GetParent(IntPtr hWnd);

        [DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
        internal static extern int GetWindowText(IntPtr hWnd, [Out, MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId")]
        public static extern uint GetWindowThreadProcessId(IntPtr hWnd, ref uint lpdwProcessId);

        [DllImport("user32.dll", EntryPoint = "IsWindow")]
        public static extern bool IsWindow(IntPtr hWnd);

        [DllImport("kernel32.dll", EntryPoint = "SetLastError")]
        public static extern void SetLastError(uint dwErrCode);


        public static IntPtr GetTheWindowHandle(string strFileName)
        {
            IntPtr hwnd = IntPtr.Zero;
            UpdateTaskWind();
            hwnd = getHwnd(strFileName);
            //StringBuilder sb = new StringBuilder(128);
            //if (hwnd == IntPtr.Zero || IsWindow(hwnd) == false)
            //    UpdateTaskWind();
            //else
            //{
            //    GetWindowText(hwnd, sb, sb.Capacity);
            //    string text = sb.ToString();
            //    GetClassName(hwnd, sb, sb.Capacity);
            //    if (!dealFileName(strFileName).Equals(dealWinText(text, sb.ToString())))
            //        UpdateTaskWind();
            //}
            //hwnd = getHwnd(strFileName);
            return hwnd;
        }

        public static IntPtr UpdateWind(IntPtr hwnd)
        {
            string strWindText = "";
            foreach (taskWind task in tasks)
            {
                if (task.hwnd == hwnd)
                {
                    strWindText = task.text;
                    break;
                }
            }
            UpdateTaskWind();
            if (!strWindText.Equals(""))
            {
                IntPtr myhwnd = IntPtr.Zero;
                foreach (taskWind task in tasks)
                {
                    if (task.text.Equals(strWindText))
                    {
                        if (task.className.Equals("screenClass"))
                            return task.hwnd;
                        if (task.className.Equals("MS-SDIb") ||
                            task.className.Equals("MS-SDIa"))
                            myhwnd = task.hwnd;
                        if (myhwnd == IntPtr.Zero)
                            myhwnd = task.hwnd;
                    }
                }
                return myhwnd;
            }
            return IntPtr.Zero;
        }
        //更新当前任务栏窗口
        public static void UpdateTaskWind()
        {
            tasks.Clear();
            EnumWindows(new WNDENUMPROC(EnumWindowsProc), 0);
        }

        private static bool EnumWindowsProc(IntPtr hwnd, int lParam)
        {
            StringBuilder sb = new StringBuilder(128);
            if (GetWindow(hwnd, 4) == IntPtr.Zero && IsWindowVisible(hwnd)) // 滤掉不在任务栏显示的窗口
            {
                GetClassName(hwnd, sb, sb.Capacity);
                string str = sb.ToString();
                if (!str.Equals("Shell_TrayWnd") // 滤掉任务栏本身
                      && !str.Equals("Progman")) // 滤掉桌面
                {
                    //这就是你想要的窗口了。
                    GetWindowText(hwnd, sb, sb.Capacity);
                    if (sb.ToString().Length > 0)
                    {
                        taskWind task = new taskWind();
                        task.hwnd = hwnd;
                        task.className = str;
                        task.text = dealWinText(sb.ToString(), task.className);
                        tasks.Add(task);
                    }
                }
            }
            return true;

        }

        public static IntPtr getHwnd(string strFileName)
        {
            IntPtr hwnd = IntPtr.Zero;
            string temp = dealFileName(strFileName);
            if (tasks == null)
                return hwnd;
            foreach (taskWind task in tasks)
            {
                if (task.text.Equals(temp))
                {
                    if (task.className.Equals("screenClass"))
                        return task.hwnd;
                    if (task.className.Equals("MS-SDIb") ||
                        task.className.Equals("MS-SDIa"))
                        hwnd = task.hwnd;
                    if (hwnd == IntPtr.Zero)
                        hwnd = task.hwnd;
                }
            }
            return hwnd;
        }
        public static string dealFileName(string strFileName)
        {
            string ret = strFileName;
            string temp = strFileName.Split('.')[1].ToLower();
            if (officeVersion.Equals("office2007") ||
                    officeVersion.Equals("office2010"))
            {
                if (temp.Equals("ppt") || temp.Equals("doc"))
                    ret += " [兼容模式]";
                if (temp.Equals("xls"))
                    ret += "  [兼容模式]";
            }
            return ret;
        }

        public static string dealWinText(string strWinText, string strClassName)
        {
            string ret = strWinText;
            int index;
            //ppt放映窗口
            if (strClassName.Equals("screenClass"))
            {
                index = ret.IndexOf(" - ");
                if (index < 0)
                    index = 0;
                else
                    index += 4;
                ret = ret.Substring(index);
                ret = ret.Substring(0, ret.Length - 1);
                return ret;
            }
            //word主窗口
            if (strClassName.Equals("OpusApp"))
            {
                index = ret.LastIndexOf(" - ");
                if (index < 0)
                    index = ret.Length;
                ret = ret.Substring(0, index);
                return ret;
            }
            //xls主窗口
            if (strClassName.Equals("XLMAIN"))
            {
                index = ret.IndexOf(" - ");
                if (index < 0)
                    index = 0;
                else
                    index += 3;
                ret = ret.Substring(index);
                return ret;
            }

            //2003和2007 ppt主窗口
            if (strClassName.Equals("PP11FrameClass") ||
                strClassName.Equals("PP12FrameClass"))
            {
                index = ret.IndexOf(" - ");
                if (index < 0)
                    index = 0;
                else
                    index += 4;
                ret = ret.Substring(index);
                ret = ret.Substring(0, ret.Length - 1);
                return ret;
            }
            //2010 ppt主窗口
            if (strClassName.Equals("PPTFrameClass"))
            {
                index = ret.LastIndexOf(" - ");
                if (index < 0)
                    index = ret.Length;
                ret = ret.Substring(0, index);
                return ret;
            }
            return ret;
        }

        // <summary>
        // 获取当前某个版本Office的安装路径
        // </summary>
        // <param name="Path">返回当前系统Office安装路径</param>
        // <param name="Version">返回当前系统Office版本信息</param>
        public static void GetOfficePath(out string Path, out string Version)
        {
            string strPathResult = "";
            string strVersionResult = "";
            string strKeyName = "Path";
            object objResult = null;
            Microsoft.Win32.RegistryValueKind regValueKind;
            Microsoft.Win32.RegistryKey regKey = null;
            Microsoft.Win32.RegistryKey regSubKey = null;

            try
            {
                regKey = Microsoft.Win32.Registry.LocalMachine;

                if (regSubKey == null)
                {//office97
                    regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\8.0\Common\InstallRoot", false);
                    strVersionResult = "office97";
                    strKeyName = "OfficeBin";
                }

                if (regSubKey == null || regSubKey.GetValue(strKeyName) == null)
                {//Office2000
                    regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\9.0\Common\InstallRoot", false);
                    strVersionResult = "office2000";
                    strKeyName = "Path";
                }

                if (regSubKey == null || regSubKey.GetValue(strKeyName) == null)
                {//officeXp
                    regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\10.0\Common\InstallRoot", false);
                    strVersionResult = "officeXP";
                    strKeyName = "Path";
                }

                if (regSubKey == null || regSubKey.GetValue(strKeyName) == null)
                {//Office2003
                    regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\11.0\Common\InstallRoot", false);
                    strVersionResult = "office2003";
                    strKeyName = "Path";
                }

                if (regSubKey == null || regSubKey.GetValue(strKeyName) == null)
                {//office2007 
                    regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\12.0\Common\InstallRoot", false);
                    strVersionResult = "office2007";
                    strKeyName = "Path";
                }

                if (regSubKey == null || regSubKey.GetValue(strKeyName) == null)
                {//office2010 
                    regSubKey = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Office\14.0\Common\InstallRoot", false);
                    strVersionResult = "office2010";
                    strKeyName = "Path";
                }

                objResult = regSubKey.GetValue(strKeyName);
                if (objResult == null)
                {
                    Path = "unknow";
                    Version = "unknow";
                    return;
                }
                regValueKind = regSubKey.GetValueKind(strKeyName);
                if (regValueKind == Microsoft.Win32.RegistryValueKind.String)
                {
                    strPathResult = objResult.ToString();
                }
            }
            catch (System.Security.SecurityException ex)
            {
                throw new System.Security.SecurityException("您没有读取注册表的权限", ex);
            }
            catch (Exception ex)
            {
                throw new Exception("读取注册表出错!", ex);
            }
            finally
            {

                if (regKey != null)
                {
                    regKey.Close();
                    regKey = null;
                }

                if (regSubKey != null)
                {
                    regSubKey.Close();
                    regSubKey = null;
                }
            }
            Path = strPathResult;
            Version = strVersionResult;
        }
    }

    //保存目前正在受到控制的应用程序的结构类
    public class appItem
    {
        public int id;
        public IntPtr hwnd;
        public string name;
    }
}
